<?php
require_once("DButil.php");

// 默认值
$pageNum = 1;
if(isset($_REQUEST["pageNum"])) {
    // 有此参数时, 使用给定的值
    $pageNum = $_REQUEST["pageNum"];
}
$pageSize = 2;

// 查询参数
$pid = $_REQUEST["pid"];
$pname = $_REQUEST["pname"];
$begin = $_REQUEST["begin"];
$end = $_REQUEST["end"];

$whereSql = "";
// " and p_id = {$pid} and p_name like '%{$pname}%' and p_price >= {$begin} and p_price <= {$end}"
// 对应参数必须有值, 且不能是空字符串 或 空白
if(isset($pid) && strlen(trim($pid))){
    $whereSql .= " and p_id = {$pid} ";
}
if(isset($pname) && strlen(trim($pname))){
    $whereSql .= " and p_name like '%{$pname}%' ";
}
if(isset($begin) && strlen(trim($begin))){
    $whereSql .= " and p_price >= {$begin} ";
}
if(isset($end) && strlen(trim($end))){
    $whereSql .= " and p_price <= {$end} ";
}

// 查询可供分页使用的总数据量
$sql = "select count(1) count from t_product where p_status = 1 " . $whereSql;
$products = query($sql);
// 总数据量
$count = $products[0]["count"];
// 总页数
$totalPage = ceil($count/$pageSize);

$m = ($pageNum - 1) * $pageSize;
$n = $pageSize;

// 查询当页的数据·
$sql = "select p_id, p_name, p_price, p_unit, p_image_url, p_status from t_product where p_status = 1 ". $whereSql ." limit {$m}, {$n}";

$productArr = query($sql);

// 返回分页的数据
$pageInfo = [
    "pageNum" => (int)$pageNum,
    "count" => (int)$count,
    "totalPage" => $totalPage,
    "list" => $productArr
];
header("Content-Type:application/json;charset=utf-8");
echo json_encode($pageInfo);
?>